const Koa = require("koa");
const Router = require("koa-router");
const WebSocket = require("ws");

const app = new Koa();
const router = new Router();

// 创建 WebSocket 服务器
const wss = new WebSocket.Server({ port: 8080 });

let clients = [];

wss.on("connection", (ws) => {
  console.log("New client connected");

  // 将新连接的客户端加入列表
  clients.push(ws);

  // 监听消息
  ws.on("message", (message) => {
    console.log("Received message:", message);

    // 广播消息给其他客户端
    clients.forEach((client) => {
      if (client !== ws && client.readyState === WebSocket.OPEN) {
        client.send(message);
      }
    });
  });

  // 处理断开连接
  ws.on("close", () => {
    console.log("Client disconnected");
    clients = clients.filter((client) => client !== ws);
  });
});

app.use(router.routes());
app.use(router.allowedMethods());

app.listen(3000, () => {
  console.log("HTTP server running on http://localhost:3000");
});